package com.info.zhiduoduo.pay.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.Condition;
import com.info.zhiduoduo.common.configs.KltPayConfig;
import com.info.zhiduoduo.common.constants.Constants;
import com.info.zhiduoduo.common.constants.SmartResult;
import com.info.zhiduoduo.common.constants.StatusMsg;
import com.info.zhiduoduo.common.formbean.BaseSimpleFormBean;
import com.info.zhiduoduo.common.utils.LogUtil;
import com.info.zhiduoduo.pay.formbean.offlinepayment.CreateOrderFormBean;
import com.info.zhiduoduo.pay.formbean.offlinepayment.QueryOrderFormBean;
import com.info.zhiduoduo.pay.sdk.kltongpaysdk.model.offlinepayment.CreateOrderContent;
import com.info.zhiduoduo.pay.sdk.kltongpaysdk.model.offlinepayment.CreateOrderRequest;
import com.info.zhiduoduo.pay.sdk.kltongpaysdk.model.offlinepayment.CreateOrderResult;
import com.info.zhiduoduo.pay.sdk.kltongpaysdk.model.offlinepayment.OfflineHead;
import com.info.zhiduoduo.pay.sdk.kltongpaysdk.model.offlinepayment.OfflinePaymentNotifyResult;
import com.info.zhiduoduo.pay.sdk.kltongpaysdk.model.offlinepayment.QueryOrderContent;
import com.info.zhiduoduo.pay.sdk.kltongpaysdk.model.offlinepayment.QueryOrderRequest;
import com.info.zhiduoduo.pay.sdk.kltongpaysdk.model.offlinepayment.QueryOrderResult;
import com.info.zhiduoduo.pay.sdk.kltongpaysdk.util.HttpUtils;
import com.info.zhiduoduo.pay.sdk.kltongpaysdk.util.RSAUtils;
import com.info.zhiduoduo.repository.dto.company.CompanyOfflineRechargeDto;
import com.info.zhiduoduo.repository.entity.company.CompanyOfflineRecharge;
import com.info.zhiduoduo.repository.entity.company.CompanyOfflineRechargeDetail;
import com.info.zhiduoduo.repository.mapper.company.CompanyOfflineRechargeMapper;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;

/**
 * 开联通线下支付转账付款
 */
@Slf4j
@Service
public class OfflinePaymentService {

	@Autowired
	CompanyOfflineRechargeMapper companyOfflineRechargeMapper;
	@Autowired
	KltPayConfig kltPayConfig;

	public SmartResult createOrder(BaseSimpleFormBean<CreateOrderFormBean> formBean) {

		CreateOrderFormBean reqdata = formBean.getReqdata();

		String s = JSON.toJSONString(reqdata);
		System.out.println("s = " + s);

		CreateOrderContent content = new CreateOrderContent();
		BeanUtils.copyProperties(reqdata, content);

		content.setCurrency("156");
		content.setNotifyUrl(kltPayConfig.getOfflinePaymentNotifyUrl());
		content.setOrderNo(reqdata.getOrderNo());

		//参数
		OfflineHead head = new OfflineHead();
		head.setMerchantId(kltPayConfig.getMerchantId()).setSignType("2").setVersion("1.0");

		CreateOrderRequest request = new CreateOrderRequest(head, content);

		JSONObject jsonObject = (JSONObject) JSONObject.toJSON(request);
		String originStr = jsonObject.toJSONString();
		LogUtil.info("请求参数, 签名前:" + originStr);
		LogUtil.info("md5key=" + kltPayConfig.getMd5Key());
		//添加签名
		// String signStr = SignUtils.addSign(originStr, kltPayConfig.getMd5Key());
		String signStr = null;
		try {
			signStr = RSAUtils.sortAndRsa256Sign(originStr, kltPayConfig.getPrivateKey());
		} catch (Exception e) {
			return SmartResult.fail(StatusMsg.StatusMsg_199);
		}
		LogUtil.info("签名后,请求参数:" + signStr);
		//忽略SSL认证
		String respJsonStr = null;
		try {
			respJsonStr = HttpUtils.sendHttpPostRequest(kltPayConfig.getOfflineCreateOrderUrl(), signStr, false);
		} catch (Exception e) {
			e.printStackTrace();
			return SmartResult.fail(e.getMessage());
		}

		LogUtil.info("返回:" + respJsonStr);
		CreateOrderResult result = JSON.parseObject(respJsonStr, CreateOrderResult.class);
		if (result == null) {
			return SmartResult.fail(StatusMsg.StatusMsg_199);
		} else if (!"000000".equals(result.getResponseCode())) {
			SmartResult smartResult = SmartResult.fail(StatusMsg.StatusMsg_452);
			smartResult.setMsg(result.getResponseMsg());
			return smartResult;
		}
		return SmartResult.success(result);
	}

	public SmartResult queryOrder(BaseSimpleFormBean<QueryOrderFormBean> formBean) {

		QueryOrderFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return SmartResult.ofErrorParam();

		OfflineHead offlineHead = new OfflineHead().setSignType("2").setVersion("1.0").setMerchantId(kltPayConfig.getMerchantId());
		QueryOrderContent content = new QueryOrderContent(reqdata.getOrderNo());
		QueryOrderRequest request = new QueryOrderRequest(offlineHead, content);

		JSONObject jsonObject = (JSONObject) JSONObject.toJSON(request);
		String originStr = jsonObject.toJSONString();
		LogUtil.info("请求参数, 签名前:" + originStr);
		LogUtil.info("md5key=" + kltPayConfig.getMd5Key());
		//添加签名
		// String signStr = SignUtils.addSign(originSign, kltPayConfig.getMd5Key());
		String signStr = null;
		try {
			signStr = RSAUtils.sortAndRsa256Sign(originStr, kltPayConfig.getPrivateKey());
		} catch (Exception e) {
			return SmartResult.fail(StatusMsg.StatusMsg_199);
		}
		LogUtil.info("签名后,请求参数:" + signStr);
		//忽略SSL认证
		String respJsonStr = null;
		try {
			respJsonStr = HttpUtils.sendHttpPostRequest(kltPayConfig.getOfflineQueryOrderUrl(), signStr, false);
		} catch (Exception e) {
			e.printStackTrace();
			return SmartResult.fail(e.getMessage());
		}

		LogUtil.info("返回:" + respJsonStr);
		QueryOrderResult result = JSON.parseObject(respJsonStr, QueryOrderResult.class);
		if (result == null) {
			return SmartResult.fail(StatusMsg.StatusMsg_199);
		} else if (!"00000".equals(result.getResponseCode())) {
			SmartResult smartResult = SmartResult.fail(StatusMsg.StatusMsg_199);
			smartResult.setMsg(result.getResponseMsg());
			return smartResult;
		}
		return SmartResult.success(result);
	}

//	public String paymentNotify(OfflinePaymentNotifyResult notifyResult) {
//		log.info("企业线下充值,开联通回调: orderNo:" +  notifyResult.getOrderNo());
//
//		boolean checkSign = RSAUtils.checkSign(JSON.toJSONString(notifyResult), kltPayConfig.getPublicKey());
//		if (!checkSign) return "wrong sign!";
//
//		String orderNo = notifyResult.getOrderNo();
//		CompanyOfflineRecharge recharge = new CompanyOfflineRecharge().selectOne(Condition.create().eq("recharge_no", orderNo));
//
//		if (recharge == null) {
//			log.info("企业线下充值,开联通回调, 没有找到订单号为[{}]的充值单", orderNo);
//			return "fail";
//		}
//
//		try {
//			CompanyOfflineRechargeDetail rechargeDetail = new CompanyOfflineRechargeDetail().selectOne(
//					Condition.create().eq("klt_detail_order_id", notifyResult.getKltOrderId()));
//			if (recharge.getState() == Constants.OFFLINE_RECHARGE_TRANSFER_FINISHED) {
//				// 转账已完成
//				if (rechargeDetail == null) {
//					// 还没有此条转账记录, 先记录下来. 特殊标记状态.
//					rechargeDetail = notifyResult.to()
//							.setOfflineRechargeId(recharge.getId())
//							.setOfflineRechargeNo(recharge.getRechargeNo())
//							.setState(3);
//					rechargeDetail.insert();
//
//				}
//			} else {
//				// 充值还未结束
//				if (rechargeDetail == null) {
//					// 没有此转账记录, 直接新建一个
//					rechargeDetail = notifyResult.to()
//							.setOfflineRechargeId(recharge.getId())
//							.setOfflineRechargeNo(recharge.getRechargeNo())
//							.setState(1);
//					rechargeDetail.insert();
//				}
//
//				// 判度当前订单,是否已结束
//				CompanyOfflineRechargeDto rechargeDto = companyOfflineRechargeMapper.findByRechargeNo(orderNo);
//				if (rechargeDto.getAmount().compareTo(rechargeDto.getTransferedAmount()) <= 0) {
//					recharge.setState(Constants.OFFLINE_RECHARGE_TRANSFER_FINISHED).updateById();
//				} else {
//					recharge.setState(Constants.OFFLINE_RECHARGE_TRANSFERING).updateById();
//				}
//			}
//
//			return "success";
//		} catch (Exception e) {
//			log.error("企业线下充值,开联通回调报错:", e);
//		}
//
//		// 返回错误, 再次推送
//		return "fail";
//	}
}
